Skip to content

Phase 3: CLI login and signup on the device flow - #1289

Merged
neuromechanist merged 21 commits into
feature/issue-1272-epic-orcid-cli-signinfrom
feature/issue-1283-phase3-cli-device-flow
Sep 7, 2026
Merged

neuromechanist merged 21 commits into
feature/issue-1272-epic-orcid-cli-signinfrom
feature/issue-1283-phase3-cli-device-flow

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

CLI half of ORCID-first sign-in (epic #1272, phase 3). nemar auth login is now the one command for first-time signup and later sign-in: it mints a device code (phase 1, ADR 0047), prints the authorize URL and the short code, tries the browser unless --no-open or NEMAR_NO_BROWSER=1, polls with the RFC 8628 backoff, and writes the key to a 0600 config file. --key and NEMAR_API_KEY remain the paste-key path for hosts that cannot open a browser. Signup drops the password and the typed ORCID iD: it is the same device flow followed by guided completion of the fields the server reports missing (username suggestion, GitHub handle, city, country, then the upload access request), each with a flag for scripts.

Other changes: accounts are keyed by username or email (a brand-new ORCID account has no username yet) and merged on re-login; a re-login replaces this machine's previous key; nemar auth logout revokes only a device-minted key by default (--revoke-key / --no-revoke-key); nemar auth keys list|create|revoke; auth status shows the key; retrieve-key and regenerate-key print a deprecation sentence; the API client learns the device vocabulary so a person reads the sentence rather than a code; device_code is redacted from debug logs; confirm() declines cleanly without a TTY; Ctrl-C mid-poll aborts the in-flight request and exits 130 with the previous config untouched. Two small backend touches: GET /auth/profile/username-suggestion accepts a bearer, and the brand-new-account ORCID redirect to /auth/orcid/complete carries ?next= so the website (nemarOrg/website#317) can return the person to the authorize page.

Closes #1283
Part of epic #1272

Test plan

  • test/auth-device-cli.test.ts (41 cases, real bun run src/index.ts against a Bun.serve stand-in): printed URL and code; browser attempted only when allowed; pending then slow_down honoured; expiry and denial as one sentence plus next step with no config write; success writes a 0600 config that auth status reads; SIGINT mid-poll leaves the config byte-identical and exits 130; two logins in flight; --key refused before any write; a 0644 config becomes 0600; logout revoke rules; keys list/create/revoke; signup with flags and its non-TTY refusal; deprecation lines; root shortcuts; debug log redaction
  • test/device-login.unit.test.ts, test/api-export-surface.unit.test.ts, test/debug-log-cli.test.ts updated; backend/test/profile-username-route.test.ts and backend/test/device-auth-routes.test.ts cover the two backend touches
  • bun run lint, bun run typecheck; full bun test matches the pre-existing baseline (the same 50 credential-dependent live-tier failures, none new)
  • Prove-the-test-fails: the slow_down step, the poll abort signal, configFileMode, the username-or-email key, the logout keySource check, the non-TTY guard; each mutation caught, each reverted
  • test/auth-device-cli-live.test.ts runs against the dev worker once the epic reaches dev (it probe-skips until then)
  • Staging walk-through from ssh mcm and ssh mba, including a headless run over ssh with the code entered on the laptop, recorded on Phase 3: CLI login and signup on the device flow #1283 after deployment

prefersMessage learns the device grant/refusal code vocabularies so
message wins; ApiError gains optional code/reason set post-construction;
debug-log redacts device_code. Part of #1283 (epic #1272 phase 3).
startDeviceAuth, pollDeviceToken, listApiKeys, createApiKey,
revokeApiKey, suggestUsername; LoginResponse.user.username is now
nullable (ADR 0047). Part of #1283 (epic #1272 phase 3).
configFileMode 0600 plus a one-time chmod migration for an existing
file; accountKeyFor, findAccountKeyByEmail, upsertAccount, and the
keyId/keyName/keyCreatedAt/keySource schema fields. Part of #1283
(epic #1272 phase 3).
confirm()/confirmWithInput() check process.stdin.isTTY before ever
calling inquirer: under stdin: "ignore" inquirer never settles and the
process dies uncatchably at exit. Part of #1283 (epic #1272 phase 3).
New src/lib/device-login.ts drives the device authorization grant:
print the URL and code, try the browser, poll for the key with a
SIGINT-cancellable, timeout-composed poll loop. loginAction rewired
onto it (the --key/NEMAR_API_KEY path stays as validated paste-key
fallback), sharing writeSignedInAccount/applyServerUser with
statusAction --refresh (now renames on refresh and prints the Key:
line) and the profile self-service commands. Exit hook suppresses the
bug-report nudge for 130 (Ctrl-C during the poll). storeAccount()
removed, its one caller moved. Part of #1283 (epic #1272 phase 3).
Default: DELETE /auth/keys/current only for a device-sourced key; a
pasted or password-era key is kept, with where to revoke it deliberately.
--revoke-key forces, --no-revoke-key skips; --all revokes each stored
account with its own bearer. Part of #1283 (epic #1272 phase 3).
list (default), create <name>, revoke <id|current> over GET/POST
/auth/keys and DELETE /auth/keys/:id|current. Part of #1283 (epic
#1272 phase 3).
GET /auth/profile/username-suggestion accepts a bearer through
resolveActingAccount, reading the name by actor.id; the ORCID
callback's brand-new-account redirect to /auth/orcid/complete carries
?next= when it names somewhere other than '/'. Part of #1283 (epic
#1272 phase 3).
nemar auth signup runs the device flow, then fills in username,
github_username, city, country via flag or prompt in one PATCH
/auth/profile, requests upload access unless --no-upload-access, and
reports anything the CLI cannot set. Non-TTY stdin names the missing
flags and exits 1 before any prompt. collectResearcherName and
lookupOrcidName are gone with the ORCID/password form. Part of #1283
(epic #1272 phase 3).
Both print a yellow sentence pointing at 'nemar auth login' before
their first prompt; regenerate-key also names that it revokes the key
on every machine, unlike logout's machine-scoped default. Part of
#1283 (epic #1272 phase 3).
test/auth-device-cli.test.ts (41 cases: URL/code/browser, polling
cadence, terminal answers, success writes the account, stale-probe
re-login, active-account re-login, SIGINT, parallel logins, the
server going away and back, --key, status file mode and rename,
logout, keys, signup completion, deprecations, root shortcuts,
--debug redaction) and test/device-login.unit.test.ts (machineName,
pollDeadlineMs, accountKeyFor). Fixes a bug the stale-probe test
caught: writeSignedInAccount was skipping the old device key's
revoke entirely when the preflight probe found it dead, instead of
only skipping the confirmation line. Part of #1283 (epic #1272
phase 3).
test/auth-device-cli-live.test.ts drives the real CLI subprocess
against a deployed backend (TEST_API_URL), streaming stdout to catch
the printed code and acting on the browser side through seedWebUser
plus the passwordless dev_code sign-in: the full login/status/keys/
logout loop, deny, a pending account's confirm refusal, a mid-flight
revoke, and signup with flags. Prod-guarded and deploy-probe-skipped
like test/auth-device-flow.test.ts; the from-scratch ORCID signup
path and the service-account case (test.todo) are out of reach for
an automated test and are recorded for the manual walk-through on
#1283. Part of #1283 (epic #1272 phase 3).
README quick start, auth command list, environment variables
(NEMAR_NO_BROWSER; drops the fictional NEMAR_API_URL), and
troubleshooting; AGENTS.md's user flow and CLI commands table; ADR
0047 Consequences for decisions 5-7, 10, 12 (account keying, the
config file's 0600 mode, same-machine key replacement, logout's
scoped revoke, and the retrieve-key/regenerate-key deprecation
replacing the ADR's deferred call). Part of #1283 (epic #1272
phase 3).
@github-actions

github-actions Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1289

Version: 0.9.17-PR1289.93dfba1
Commit: 93dfba1


🤖 Updated on each push.

writeSignedInAccount's greeting now depends on source: --key/
NEMAR_API_KEY keeps the pre-phase-3 "Welcome back, <name>!" (a person
pasting a key already holds an account); the device flow keeps the
new "Welcome, <name>!". Pinned in test/auth-device-cli.test.ts: the
--key good case asserts "Welcome back", a device success asserts
"Welcome," and not "Welcome back". Fixes the integration-dev
failure on PR #1289 (test/cli.test.ts:230).
applyServerUser now caches sandbox_dataset_id when the server sends
one, restoring behavior the paste path had before this phase.
Pinned through both login paths with a returning trained account;
the stand-in's defaultUser() no longer defaults to a fresh account,
so a caller that forgets to cache it fails loudly.
Only a network failure (statusCode 0) prints the "unreachable"
retry line and waits out the deadline. Any other thrown error --
a 5xx, a 200 that fails deviceTokenSuccessSchema, or a 400 with an
unrecognized code -- is now counted; three in a row end the poll
with a new "server_error" outcome instead of retrying silently
until the deadline. A success resets the count.

Also spreads the success payload before the "kind" discriminant
({ ...result.data, kind: "success" }) so a passthrough field can
never overwrite it.
pollDeviceToken now re-parses the token endpoint's 400 body against
deviceTokenErrorSchema (a discriminated union) instead of probing
error/reason as loose strings. reason is typed
DeviceAuthRefusalCode | undefined and is never backfilled from
error -- it is undefined only when the body itself failed to
validate.

A 400 whose error is still a terminal grant code this build
recognizes ends the poll even when the body fails validation,
using the body's own message when present, else
DEVICE_GRANT_MESSAGES[error].

ApiError gains rawBody (the whole parsed error body), set by
request() alongside the existing code/reason fields, so a caller
that needs the full contract shape has it without every other
caller paying for a second body it never asked for.
Config's key fields (keyId/keyName/keyCreatedAt/keySource) become a
discriminated union (KeyFields in lib/config.ts): a "device" entry
always carries all three, a "paste" entry carries none, and absent
keySource is a password-era account. writeSignedInAccount takes a
single tagged keyInfo parameter instead of two separately-typed
ones that happened to always agree, so the invalid "device with no
key" state cannot be constructed. A paste login explicitly clears a
stale device key's fields rather than merely omitting them, so a
re-login on a different path from the same machine cannot leave a
no-longer-current keyId behind.

AccountInfo gains "key" (the accounts-map key) and makes "username"
honestly optional -- an email-keyed entry has none. switchAction's
picker, logoutAction --all, and the "Other accounts" status line
now use "key" to look up and revoke accounts instead of a username
that could be undefined; --all previously skipped an email-keyed
account entirely (switchAccount(undefined) finds nothing), which a
new regression test with a mixed username/email-keyed fleet covers.

Also prints a visible warning when the same-machine key revoke on
login fails, instead of swallowing the error silently.
findAccountKeyByEmail returns undefined (not a guess) when two
stored entries share an email, and dlogs the ambiguity -- a state
this build never writes on its own, so guessing which one a
re-login means risks merging the wrong account's key and cached
fields into it. upsertAccount's caller lands the login as a fresh
entry instead, same as no match.

writeSignedInAccount now catches upsertAccount throwing (a corrupt
store, an unwritable config dir): the sign-in already succeeded
server-side, so a just-minted device key is best-effort revoked
with itself as bearer (new revokeApiKeyWithBearer, since nothing
was ever saved to authenticate the ordinary way) before reporting
the failure and exiting 1, instead of an uncaught exception.
Removes every "(decision N)" citation from the phase 3 device-flow
files: each either cites ADR 0047 by content where the ADR actually
covers the rule, or states the rule plainly where it does not (the
plan's own numbering is not something a future reader can verify
against). Fixes the matching phase 1 leftover in
backend/src/services/device-auth.ts.

AGENTS.md's CLI table now shows -k/--key on login only, not signup.
The auth/keys group verbose help spells out that a browser-based
login mints a key while --key/NEMAR_API_KEY only stores one.
retrieve-key/regenerate-key's verbose help gains the deprecation
sentence and regenerate-key's every-machine warning.
guardNonInteractive's docstring now points at confirm()'s guard
instead of independently restating the inquirer failure mode.
test/auth-device-cli-live.test.ts cites
.github/workflows/deploy-backend.yml's push trigger instead of
"AGENTS.md release pipeline" for why the dev worker deploys only
from dev.

config.ts: a named CONFIG_FILE_MODE constant replaces two 0o600
literals; "conf's pre-13 default" becomes "conf's default file mode
(0o666, unrelated to the conf version)" in both config.ts and ADR
0047. ADR 0047 also names MAX_LIVE_API_KEYS where the 25-key cap is
discussed, rejoins a mid-clause line break at the em dash, and
splits an over-long line before its parenthetical.
Live test: seedWebUser now returns the seeded row's id, and the
mid-flight-revoke test uses it against POST /admin/revoke/by-id/:id
with an asserted 200 instead of a best-effort, swallowed call.

CLI test: a password-era flat config (no "accounts" key) is migrated
in place, read by auth status (with its password-era Key: line),
and merged into by a later device login rather than duplicated. A
live (not stale) device key's same-machine re-login still revokes
and prints the replacement confirmation. invalid_grant/too_many_keys
is covered alongside the other terminal codes. A SIGINT with a
seeded config leaves the file byte-identical. /users/me stand-in
bodies are typed from the contract (UserMeResponse) and re-parsed
against userMeResponseSchema before being served, so a contract
drift fails the file instead of silently serving a stale shape. The
polling-gap assertion is loosened to the actual invariant (slow_down
roughly doubles the gap) rather than a fixed millisecond floor.

pollForDeviceToken/pollDeadlineMs take an optional graceSeconds,
defaulting to DEVICE_CONFIRM_GRACE_SECONDS and never passed by the
real CLI entry point. A new unit test calls it with graceSeconds: 0
against a closed port and gets "unreachable" in about a second,
covering the deadline-reached give-up branch the CLI stand-in test
cannot reach without waiting out the real multi-minute window; the
CLI test file notes why at the relevant section.
@neuromechanist
neuromechanist merged commit b54df98 into feature/issue-1272-epic-orcid-cli-signin Sep 7, 2026
12 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-1283-phase3-cli-device-flow branch September 7, 2026 12:59

This branch was previously deployed

1 inactive deployment
npm — 93dfba1b Deployed Sep 7, 2026 by neuromechanist via publish #2353
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant